#coding=utf-8

import re,urllib2
import hashlib
from debug import logprint
import datetime,time
import model
from model import get_code_need,update_daily_quote

today=datetime.date.today()
cyear=str(today)[:4]

MINDAYS=5
BUYTRIG=3
SELLTRIG=3
RATE_LEVEL={'5':"Buy",
            '4':'Outperform',
            '3':'Neutral',
            '2':'Underperform',
            '1':'Sell'}


def sortedDictValues(adict):
    keys = adict.keys()
    keys.sort(reverse=False)
    #return [adict[key] for key in keys]
    return [(key,adict[key]) for key in keys]

def sortedDictValues2(adict): 
    keys = adict.keys() 
    keys.sort() 
    return map(adict.get,keys)

def sortedDictValues3(adict): 
    return sorted(adict.items(), key=lambda e:e[0], reverse=False)



def hash_gen(drawstr):
    
    #md5 = hashlib.md5() #创建一个MD5加密对象  
    #md5.update("JGood is a handsome boy")  #更新要加密的数据  
    return hashlib.new("md5", drawstr).hexdigest()

#定义求和函数
def grades_sum(grades):
    total = 0
    for grade in grades: 
        total += grade[0]
    return total
#定义求平均值函数   
def grades_average(grades):
    sum_of_grades = grades_sum(grades)
    average = sum_of_grades / float(len(grades))
    return average
#定义求方差函数
def grades_variance(scores):
    average=grades_average(scores)
    variance=0
    for score in scores:
        variance+=(average-score)**2
    return variance/len(scores)
#定义求标准差函数    
def grades_std_deviation(variance):
    return variance**0.5


def trend_decide(ranks):
    
    length_ranks=len(ranks)
    halflen=length_ranks/2 
    if length_ranks>1:
        #前半部分5日均线
        avg_rank1=grades_average(ranks[:halflen])
        #后半部分5日均线
        avg_rank2=grades_average(ranks[halflen:])
        #如果5日均线下降则触发TRIG，否则不触发
        #排名在200名内且后半段均值小于前半段均值
        if avg_rank1<=200 and avg_rank1<avg_rank2:
            #上升趋势
            TREND=True
        else:
            #下降趋势
            TREND=False
    else:
        TREND='Invaild'
        
    return TREND

def week_trend(code):
    #5日均线判断
    week_ranks=model.get_tlpm_week_ranks(code,10)
    trend_week=trend_decide(week_ranks)
    
    return trend_week

def month_trend(code):
    #10日均线判断
    month_ranks=model.get_tlpm_month_ranks(code,20)
    trend_month=trend_decide(month_ranks)
    
    return trend_month
    

def dmonth_trend(code):
    #20日均线判断
    dmonth_ranks=model.get_tlpm_month_ranks(code,40)
    trend_dmonth=trend_decide(dmonth_ranks)
    
    return trend_dmonth
    
    
def combined_rate_decide(code):
    TREND_WEEK=week_trend(code)
    TREND_MONTH=month_trend(code)
    TREND_DMONTH=dmonth_trend(code)
    
    if TREND_MONTH:
        if TREND_WEEK:
            if TREND_DMONTH:
                RATE=5 #buy买进
            else:
                RATE=4 #outperform增持
        else:
            RATE=2 #underperform 减持
    else:
        if TREND_WEEK:
            RATE=3 #neutral 中性
        elif TREND_WEEK=='Invalid':
            RATE=0
        elif TREND_DMONTH:
            RATE=2
        else:
            RATE=1 #sell 卖出
            
    return RATE


def daily_monitor_run():
    #week rang monitor
    codelist=get_code_need()
    
    for code in codelist:
        rate=combined_rate_decide(code[0])
        logprint(str(rate))
        model.update_daily_rate(code[0],rate)

def trade_data(code,direction):
    group='default'
    qty=str(100)
    price_date=model.get_price_bycode(code)
    #logprint(price_date)
    
    trade_dict={'code':code,
                'group':group,
                'code_group':hash_gen(str(code)+str(group)+str(price_date)),
                'direction':direction,
                'price':price_date[0][0],
                'qty':qty,
                'date':price_date[0][1]}
    
    logprint(trade_dict)
    
    return trade_dict    
    
def daily_trig():
    codelist=model.get_code_need()
    for code in codelist:
        rates=model.get_rates_bycode(code[0],5)
        if len(rates)<MINDAYS:#不足5各不处理
            logprint('No trig:'+code[0])
        else:
            buycount=0
            sellcount=0
            for rate in rates:
                if rate<3:
                    buycount+=1
                elif rate>3:
                    sellcount+=1
            
            if buycount>=BUYTRIG:
                logprint('Strong B:' +code[0])
                direction=1
                tdata=trade_data(code[0],direction)
                model.trade_trig(tdata)
            elif sellcount>=SELLTRIG:
                logprint('Strong S:' +code[0])
                direction=-1
                tdata=trade_data(code[0],direction)
                model.trade_trig(tdata)
                
            

if __name__ == "__main__":
    #hashtest()
    #get_org_htmlstr()
    daily_monitor_run()
    daily_trig()